package com.oneraku.service.listener;

import com.oneraku.service.domain.VerifyCodeRecord;
import com.oneraku.service.service.IVerifyCodeRecordService;
import com.oneraku.service.utils.Const;
import com.oneraku.service.utils.RequestUserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @Author: hui.ren@huberbuy.com
 * @Date: 2020/3/10 19:17
 */
@Slf4j
@Component
public class MailListener {
    @Value("${spring.mail.username}")
    private String from;
    private JavaMailSender javaMailSender;
    private IVerifyCodeRecordService verifyCodeRecordService;
    @Autowired
    public MailListener(JavaMailSender javaMailSender,IVerifyCodeRecordService verifyCodeRecordService) {
        this.javaMailSender = javaMailSender;
        this.verifyCodeRecordService = verifyCodeRecordService;
    }
    @Async
    @EventListener
    public void processBatchSendCouponEvent(MailEvent mailEvent) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(from);
        mailMessage.setTo(mailEvent.getMail());
        mailMessage.setSubject("一乐集货转运邮箱验证码");
        mailMessage.setText("您的验证码为："+mailEvent.getVerifyCode()+",验证码有效期5分钟");
        javaMailSender.send(mailMessage);
        VerifyCodeRecord record =  new VerifyCodeRecord();
        record.setCode(mailEvent.getVerifyCode());
        record.setExpire(System.currentTimeMillis()+ Const.EXPIRE_VERIFY);
        record.setUid(RequestUserUtils.getUser().getId());
        record.setType(mailEvent.getType());
        record.setNumber(mailEvent.getMail());
        verifyCodeRecordService.save(record);
    }
}
